const fs = require('fs');
const path = require('path');
const minify = require('html-minifier').minify;
const { program } = require('commander');

// 配置命令行参数
program
  .name('html-compressor')
  .description('高效压缩HTML文件的工具')
  .version('1.0.0')
  .argument('<input>', '输入HTML文件路径')
  .option('-o, --output <output>', '输出文件路径', '')
  .option('--collapse-whitespace', '压缩空白字符', true)
  .option('--remove-comments', '移除HTML注释', true)
  .option('--minify-css', '压缩内嵌CSS', true)
  .option('--minify-js', '压缩内嵌JavaScript', true)
  .option('--remove-attribute-quotes', '移除不必要的属性引号', true)
  .option('--remove-redundant-attributes', '移除冗余属性', true)
  .option('--use-short-doctype', '使用短DOCTYPE', true)
  .parse();

const options = program.opts();
const inputFile = program.args[0];
const outputFile = options.output || 
  path.join(
    path.dirname(inputFile), 
    path.basename(inputFile, '.html') + '.min.html'
  );

// 读取HTML文件
fs.readFile(inputFile, 'utf8', (err, htmlContent) => {
  if (err) {
    console.error(`❌ 读取文件失败: ${err.message}`);
    process.exit(1);
  }

  try {
    // 压缩HTML
    const compressedHtml = minify(htmlContent, {
      collapseWhitespace: options.collapseWhitespace,
      removeComments: options.removeComments,
      minifyCSS: options.minifyCss,
      minifyJS: options.minifyJs,
      removeAttributeQuotes: options.removeAttributeQuotes,
      removeRedundantAttributes: options.removeRedundantAttributes,
      useShortDoctype: options.useShortDoctype
    });

    // 写入输出文件
    fs.writeFile(outputFile, compressedHtml, 'utf8', (err) => {
      if (err) {
        console.error(`❌ 写入文件失败: ${err.message}`);
        process.exit(1);
      }
      
      // 计算压缩率
      const originalSize = Buffer.byteLength(htmlContent, 'utf8');
      const compressedSize = Buffer.byteLength(compressedHtml, 'utf8');
      const compressionRatio = (1 - compressedSize / originalSize) * 100;
      
      console.log(`✅ 成功压缩文件: ${inputFile} → ${outputFile}`);
      console.log(`📊 压缩率: ${compressionRatio.toFixed(2)}%`);
      console.log(`💾 原始大小: ${formatBytes(originalSize)} → 压缩后: ${formatBytes(compressedSize)}`);
    });

  } catch (e) {
    console.error(`❌ 处理过程中出错: ${e.message}`);
    process.exit(1);
  }
});

// 辅助函数：格式化文件大小
function formatBytes(bytes, decimals = 2) {
  if (bytes === 0) return '0 Bytes';
  
  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}    